/*
 * 文件名：SysUserController.java
 * 版权：Copyright by will_awoke
 * 描述：
 * 修改人：will_awoke
 * 修改时间：2014-6-4
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.qbgs.rbac.controller;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qbgs.base.BaseResult;
import com.qbgs.base.SimpleBaseResult;
import com.qbgs.base.TreeEntity;
import com.qbgs.constant.GlobalConstant;
import com.qbgs.rbac.service.RoleService;
import com.qbgs.rbac.service.SystemService;
import com.qbgs.rbac.service.UserService;
import com.qbgs.security.MD5;


/**
 * 
 * @author will_awoke
 * @version 2014-6-4
 * @see SysUserController
 * @since
 */
@Controller
@RequestMapping(value = "sysUser")
public class SysUserController
{

    /**
     * 日志
     */
    private static final Logger log = Logger.getLogger(SysUserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private RoleService roleService;

    /**
     * 菜单http跳转用户管理页面
     * @return 
     * @see
     */
    @RequestMapping(value = "/toView.do")
    public String toView()
    {
        return "rbac/sysUser";
    }

    /**
     * ajax分页查询。
     * 方法体不throws exception
     * 使用try catch，封装操作提示语，用于页面ajax提示
     * @return 
     * @see
     */
    @RequestMapping(value = "/userList.do")
    @ResponseBody
    public BaseResult userList(HttpServletRequest request)
    {
        BaseResult result = new BaseResult();
        try
        {
            //page：当前页    rows：每页显示记录条数  区别结果集存放List-rows
            int page = ServletRequestUtils.getIntParameter(request, "page", 1);
            int rows = ServletRequestUtils.getIntParameter(request, "rows", 10);
            String loginName = ServletRequestUtils.getStringParameter(request, "login_name", "");

            result = userService.queryUserPage(page, rows, loginName.trim());
        }
        catch (Exception e)
        {
            //出现异常，则捕获该异常，打印日志并封装ajax页面提示信息。
            result.setSuccess(false);
            result.setOpMsg(GlobalConstant.QUERRY_ERROR);
            log.error(e.toString() + " : " + e.getMessage());
        }
        return result;
    }

    /**
     * 加载角色ztree
     * @return 
     * @see
     */
    @RequestMapping(value = "/ztreeRoles.do")
    @ResponseBody
    public List<TreeEntity> ztreeRoles()
    {
        return roleService.ztreeAllRoles();
    }

    /**
     * 新增用户
     * @param request
     * @return 
     * @see
     */
    @RequestMapping(value = "/addUser.do")
    @ResponseBody
    public SimpleBaseResult addUser(HttpServletRequest request)
    {
        SimpleBaseResult result = new SimpleBaseResult();
        try
        {
            String login_name = ServletRequestUtils.getStringParameter(request, "login_name", "");
            String real_name = ServletRequestUtils.getStringParameter(request, "real_name", "");
            String email = ServletRequestUtils.getStringParameter(request, "email", "");
            String remarks = ServletRequestUtils.getStringParameter(request, "remarks", "");
            String selectRole = ServletRequestUtils.getStringParameter(request, "selectRole", "");

            //判断用户名是否重复
            if (userService.judgeLoginNameUnique(login_name))
            {
                return new SimpleBaseResult(false, GlobalConstant.USER_ADD_LOGIN_NAME_EXIST);
            }
            //执行新增操作
            boolean flag = userService.addUserOfRole(login_name,
                MD5.toMD5(GlobalConstant.DEFAULT_PASSWORD), real_name, email,
                GlobalConstant.USER_STATUS_NORMAL, remarks, selectRole);
            if (flag)
            {
                result.setOpMsg(GlobalConstant.INSERT_SUCCESS);
            }
            else
            {
                result.setSuccess(false);
                result.setOpMsg(GlobalConstant.INSERT_FAILED);
            }
        }
        catch (Exception e)
        {
            //出现异常，则捕获该异常，打印日志并封装ajax页面提示信息。
            result.setSuccess(false);
            result.setOpMsg(GlobalConstant.INSERT_ERROR);
            log.error(e.toString() + " : " + e.getMessage());
        }
        return result;
    }

    /**
     * 获得用户所绑定的角色名
     * @return 
     * @see
     */
    @RequestMapping(value = "/bindedRoles.do")
    @ResponseBody
    public BaseResult bindedRoles(HttpServletRequest request)
    {
        BaseResult result = new BaseResult();
        try
        {
            String userId = ServletRequestUtils.getStringParameter(request, "user_id", "");
            String roleIds = userService.queryRoleIdsOfUser(userId);
            String roleNames = userService.queryRoleNamesOfUser(userId);

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("roleNames", roleNames);
            data.put("roleIds", roleIds);
            result.setData(data);
        }
        catch (Exception e)
        {
            result.setSuccess(false);
            result.setOpMsg(GlobalConstant.QUERRY_ERROR);
            log.error(e.toString() + " : " + e.getMessage());
        }
        return result;
    }

    /**
     * 注销用户
     * @return 
     * @see
     */
    @RequestMapping(value = "/deleteUser.do")
    @ResponseBody
    public SimpleBaseResult deleteUser(HttpServletRequest request)
    {
        //TODO 此处删除为逻辑删除，即修改用户状态为注销，而且不删除用户所绑定的角色关系
        SimpleBaseResult result = new SimpleBaseResult();
        try
        {
            String userId = ServletRequestUtils.getStringParameter(request, "user_id", "");

            //执行删除操作
            boolean flag = userService.deleteUser(userId);
            if (flag)
            {
                result.setOpMsg(GlobalConstant.DELETE_SUCCESS);
            }
            else
            {
                result.setSuccess(false);
                result.setOpMsg(GlobalConstant.DELETE_FAILED);
            }
        }
        catch (Exception e)
        {
            result.setSuccess(false);
            result.setOpMsg(GlobalConstant.DELETE_ERROR);
            log.error(e.toString() + " : " + e.getMessage());
        }
        return result;
    }

    /**
     * 修改时，加载角色ztree
     * @return 
     * @see
     */
    @RequestMapping(value = "/ztreeEditRoles.do")
    @ResponseBody
    public List<TreeEntity> ztreeEditRoles(HttpServletRequest request)
    {
        try
        {
            String userId = ServletRequestUtils.getStringParameter(request, "user_id", "");
            return roleService.ztreeEditRoles(userId);
        }
        catch (Exception e)
        {
            log.error(e.toString() + " : " + e.getMessage());
        }
        return null;
    }

    /**
     * 修改用户
     * @return 
     * @see
     */
    @RequestMapping(value = "/editUser.do")
    @ResponseBody
    public SimpleBaseResult editUser(HttpServletRequest request)
    {
        SimpleBaseResult result = new SimpleBaseResult();
        try
        {
            String user_id = ServletRequestUtils.getStringParameter(request, "user_id", "");
            String login_name = ServletRequestUtils.getStringParameter(request, "login_name", "");
            String real_name = ServletRequestUtils.getStringParameter(request, "real_name", "");
            String email = ServletRequestUtils.getStringParameter(request, "email", "");
            String remarks = ServletRequestUtils.getStringParameter(request, "remarks", "");
            String selectRole = ServletRequestUtils.getStringParameter(request, "selectRole", "");

            //执行修改操作
            boolean flag = userService.updateUserOfRole(user_id, login_name, real_name, email, remarks, selectRole);
            if (flag)
            {
                result.setOpMsg(GlobalConstant.EDIT_SUCCESS);
            }
            else
            {
                result.setSuccess(false);
                result.setOpMsg(GlobalConstant.EDIT_FAILED);
            }
        }
        catch (Exception e)
        {
            //出现异常，则捕获该异常，打印日志并封装ajax页面提示信息。
            result.setSuccess(false);
            result.setOpMsg(GlobalConstant.EDIT_ERROR);
            log.error(e.toString() + " : " + e.getMessage());
        }
        return result;
    }

    /**
     * 重置密码
     * @return 
     * @see
     */
    @RequestMapping(value = "/resetPwd.do")
    @ResponseBody
    public SimpleBaseResult resetPwd(HttpServletRequest request)
    {
        SimpleBaseResult result = new SimpleBaseResult();
        try
        {
            String login_name = ServletRequestUtils.getStringParameter(request, "login_name", "");

            //重置密码
            boolean flag = userService.updateUserPwd(login_name, MD5.toMD5(GlobalConstant.DEFAULT_PASSWORD));
            if (flag)
            {
                result.setOpMsg(GlobalConstant.RESET_PWD_SUCCESS);
            }
            else
            {
                result.setSuccess(false);
                result.setOpMsg(GlobalConstant.RESET_PWD_FAILED);
            }
        }
        catch (Exception e)
        {
            //出现异常，则捕获该异常，打印日志并封装ajax页面提示信息。
            result.setSuccess(false);
            result.setOpMsg(GlobalConstant.RESET_PWD_ERROR);
            log.error(e.toString() + " : " + e.getMessage());
        }
        return result;
    }

    
    /**
     * ajax修改用户登录密码
     * @return 
     * @see
     */
    @RequestMapping(value = "/editPwd.do")
    @ResponseBody
    public SimpleBaseResult editPwd(HttpServletRequest request)
    {
        SimpleBaseResult result = new SimpleBaseResult();
        try
        {
            // 获得当前用户
            String loginName = (String)request.getSession().getAttribute(
                GlobalConstant.AUTH_SESSION_USERNAME_KEY);

            String oldpwd = ServletRequestUtils.getStringParameter(request, "oldpwd", "");
            String newpwd = ServletRequestUtils.getStringParameter(request, "newpwd", "");
            String renewpwd = ServletRequestUtils.getStringParameter(request, "renewpwd", "");

            //判断原始密码是否正确
            boolean isRight = systemService.isExists(loginName, oldpwd);

            //原始密码不正确 则直接提示之
            if (!isRight)
            {
                return new SimpleBaseResult(false, GlobalConstant.CHANGE_PWD_OLD_IS_WRONG);
            }
            //新密码确认密码两次输入一致  则给出提示
            if (!StringUtils.equals(newpwd, renewpwd))
            {
                return new SimpleBaseResult(false, GlobalConstant.CHANGE_PWD_NEWS_NOT_EQUALS);
            }
            //新密码等于系统默认密码  则给出提示
            if (StringUtils.equals(newpwd, GlobalConstant.DEFAULT_PASSWORD))
            {
                return new SimpleBaseResult(false, GlobalConstant.CHANGE_PWD_NEW_IS_DEFAULT);
            }
            boolean flag = userService.updateUserPwd(loginName, MD5.toMD5(newpwd));
            //修改密码成功
            if (flag)
            {
                return new SimpleBaseResult(true, GlobalConstant.CHANGE_PWD_SUCCESS);
            }
            //修改密码失败
            else
            {
                return new SimpleBaseResult(false, GlobalConstant.CHANGE_PWD_FAILED);
            }
        }
        catch (Exception e)
        {
            result.setSuccess(false);
            result.setOpMsg(GlobalConstant.CHANGE_PWD_ERROR);
            log.error(e.toString() + " : " + e.getMessage());
        }
        return result;
    }

}
